package com.mutual.assistance.user.service.impl;


import com.mutual.assistance.exception.BizException;
import com.mutual.assistance.user.constant.RedisConstant;
import com.mutual.assistance.user.service.CodeService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyuxin
 * @version 1.0
 * @description 验证码服务实现类
 * @date 2023/4/24 18:55
 */
@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String NO_CACHE = "No-cache";


    @Override
    public void getCode(HttpServletResponse response) {
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        response.setHeader(HttpHeaders.PRAGMA, NO_CACHE);
        response.setHeader(HttpHeaders.CACHE_CONTROL, NO_CACHE);
        response.setDateHeader(HttpHeaders.EXPIRES, 0L);

        Captcha captcha = new ArithmeticCaptcha(115, 42);
        captcha.setCharType(2);
        String code = captcha.text();
        log.info("获取到验证码：{}", code);
        stringRedisTemplate.opsForValue().set(RedisConstant.REGISTER_CODE_KEY, code, 5, TimeUnit.MINUTES);

        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            throw new BizException("验证码写回异常");
        }
    }
}
